package com.book.service.impl;

import com.book.entity.BookCart;
import com.book.mapper.BookCartMapper;
import com.book.service.CartService;
import com.book.vo.CartVo;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @program:
 * @ClassName:
 * @description:
 * @author: zgc
 * @date:
 * @Version 1.0
 **/
@Service
public class CartServiceImpl implements CartService {
    @Resource
    private BookCartMapper bookCartMapper;

    @Override
    public int addToCart(BookCart bookCart) {
        //如果此用户id和书籍id已存在在购物车里,则是更新数量操作
        //根据用户id和书籍id去查找,而且此记录未删除isdelete=0
        Example example = new Example(BookCart.class);
        example.createCriteria().andEqualTo("userId",bookCart.getUserId())
                .andEqualTo("bookId",bookCart.getBookId())
                .andEqualTo("isDelete",0);
        BookCart cart = bookCartMapper.selectOneByExample(example);
        
        if (cart!=null) {
            //更新数量操作
            cart.setBuyCount(cart.getBuyCount() + bookCart.getBuyCount());
            cart.setCreateTime(new Date());
            return bookCartMapper.updateByPrimaryKeySelective(cart);
        }else{
            //没有,则插入此条数据
            bookCart.setCreateTime(new Date());
            return bookCartMapper.insertSelective(bookCart);
        }
    }

    //根据用户id查询其购物信息
    @Override
    public List<CartVo> findCartByUserId(Integer userId) throws Exception {
        return bookCartMapper.selectBookCartByUserId(userId);
    }

    @Override
    public int findCartCountByUserId(Integer userId) throws Exception {
        return bookCartMapper.selectCartCountByUserId(userId);
    }
}
